/*
 * Copyright (C) 2004-2006 nickyb@users.sourceforge.net
 * 
 * This file is part of FreeQueryBuilder (http://querybuilder.sourceforge.net)
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package net.sourceforge.querybuilder;

import java.awt.BorderLayout;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import javax.swing.JFrame;

public class MainWindow extends JFrame
{
	public static final String TITLE = "FreeQueryBuilder 1.0 [ http://querybuilder.sourceforge.net ]";
	
	QueryBuilder builder;
	
	MainMenubar menubar;
	MainStatusbar statusbar;
	
	public MainWindow()
	{
		super(TITLE);
		
		getContentPane().add(builder = new QueryBuilder(), BorderLayout.CENTER);
		getContentPane().add(statusbar = new MainStatusbar(), BorderLayout.SOUTH);
		
		setJMenuBar(menubar = new MainMenubar(this));
		
		setSize(getToolkit().getScreenSize());
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}
	
	void openConnection(ClassLoader l, String drv, String url, String uid, String pwd)
		throws ClassNotFoundException, SQLException
	{
		Connection connection = null;
		
		if(builder.getConnection() != null)
			builder.getConnection().close();
		
		if(l==null)
		{
			Class.forName(drv);
			connection = DriverManager.getConnection(url,uid,pwd);
		}
		else
		{
			Class c = Class.forName(drv,true,l);
			try
			{
				Properties info = new Properties();
				
				if (uid != null) {
					info.put("user", uid);
				}
				if (pwd != null) {
					info.put("password", pwd);
				}
	
				Driver d = (Driver)c.newInstance();
				connection = d.connect(url,info);
			}
			catch (InstantiationException e)
			{
				e.printStackTrace();
			}
			catch (IllegalAccessException e)
			{
				e.printStackTrace();
			}
			
		}
		
		builder.setConnection(connection);
		statusbar.connectionChanged(url,uid);
	}
	
	void openConnection(String drv, String url, String uid, String pwd)
		throws ClassNotFoundException, SQLException
	{
		openConnection(null,drv,url,uid,pwd);
	}
	
	public static void main(String[] args)
	{
		new MainWindow().show();
	}
}
